<?php


namespace app\model;

use fast\Http;
use think\facade\Log;
use think\Model;

class Aizone extends Model {
    public  function get_token($areaname,$force=0){
        $name_id=$this->where("name_code",$areaname)->find();

        if(!$name_id) return ['error' => 'Unauthorized'];

        $expires_in=$name_id->expires_in;
        $client_id=$name_id->client_id;
        $client_sercet=$name_id->client_sercet;
        //$refreshtoken=$name_id->refresh_token;

        //$retrun = $this->register_token($username,$password,$client_id,$client_sercet,$areaname);
        if($force){
            $expires_in=0;
        }

        if($expires_in){
            $time = time();
            if($time > $expires_in){
                $retrun = $this->register_token($client_id,$client_sercet,$areaname); //没有该数据，远程获取
                if( isset( $retrun->value ) ){
                    $access_token=$retrun->value;
                }else{
                    Log::error('获取Token失败:'.$name_id->id);
                    $access_token=$name_id->access_value; //从数据库中获取access_token
                }
            }else{
                $access_token=$name_id->access_value; //从数据库中获取access_token
            }
        }else {
            $retrun = $this->register_token($client_id,$client_sercet,$areaname); //没有该数据，远程获取
            if( isset( $retrun->value ) ){
                $access_token=$retrun->value;
            }else{
                Log::error('获取Token失败:'.$name_id->id);
                $access_token=$name_id->access_value; //从数据库中获取access_token
            }
        }

        if(strlen($access_token)<=5){
            $retrun=$this->register_token($client_id,$client_sercet,$areaname);
            $access_token=$retrun->value;
        }
        return $access_token;
    }

    public function register_token($client_id, $client_sercet, $areaname) {
        $url='https://ezc.chinapopin.com/zhxq-center/oauth/token?client_id='.$client_id.'&client_secret='.$client_sercet.'&grant_type=client_credentials&scope=community';

        $return=Http::post($url);
        Log::info("token::::".$return);
        $return=json_decode($return);

        if( isset( $return->value ) ){
            $time = time()+$return->expiresIn;
            $update_sql= array(
                'access_value'=>$return->value,
                'token_type'=>$return->tokenType,
                'refresh_token'=>$return->refreshToken,
                'expires_in'=>$time,
                'jti'=>$return->additionalInformation->jti
            ); //登录
            $this->where('name_code',$areaname)->update($update_sql);
            return $return;
        }
        else
        {

            return $return;
        }
    }
}